<template>
	<view :style="viewColor" >
		<view class="pb-100">
			<view   class="bg-white p-20 mt-10 ml-10 mr-10 br-10" style="padding-right: 40px;">
				<view   class="text-black ft-w600 display-flex display-flex-align-center">
					<view class="">
						<text class=" mr-5">{{mdStartDate}}</text>
						<text class=" text-16">{{mdStartDateDsc}}</text>
					</view>
					<view class="color-999 mr-5 ml-5 ft-w700">
						-
					</view>
					<view class="">
						<text class=" text-16 mr-5">{{mdEndDate}}</text>
						<text  class=" text-16 ">{{mdEndDateDsc}}</text>
					</view>
					<view class="color-999  mr-5 ml-5 ft-w700">
						|
					</view>
					<view class=" text-16">
						<text>{{dayCount}}晚</text>
					</view>
				</view>
				<view  class="text-black ft-w600  mt-10 line2">
					<text class=" ">{{roomInfo.name}}</text>
					<text class="color-999  mr-5 ml-5 ft-w700">
						|
					</text>
					<text class=" ">{{roomInfo.bed_type}}</text>
					<text class="color-999  mr-5 ml-5 ft-w700">
						|
					</text>
					<text class=" mr-5">{{packageInfo.name}}</text>
				</view>
				<view class="text-cancel mt-5">
					入住当天{{hotelInfo.refund_time}}前可免费取消
				</view>
			</view>
			<view class="bg-white p-20 mt-10 ml-10 mr-10 br-10" >
				<view  class=" display-flex display-flex-align-center">
					<view class="source_content flex-1">
						<text class="ft-w700 text-black mr-2 text-16">订房信息</text>
					</view>
					<view class="ml-20 choice_options_wrapper display-flex display-flex-align-center">
						<number-box 
						:min="1" 
						:max="10" 
						:value="roomNum" 
						:index="1"
						 :isPlusDis="roomNum==10"
						 unit="间"
						@add="addNum"
						@minus="minusNum">
						</number-box>
					</view>
				</view>
				<view class="li-item">
					<view class="name-box">
						<view class="name-item" v-for="(item,index) in roomNameList" :key="index">
							<view class="m-label">
								<text>房间{{item.roomKey}}</text>
							</view>
							<view class="m-txt">
								<view class="input-box">
									<input type='text' placeholder='请输入姓名' v-model="item.roomName"></input>
								</view>
							</view>
							
						</view>
					</view>
					<view @click="selectPaShow" class="iconfont icon-ic_user-3 guest-icon">
						
					</view>
				</view>
				<view class="li-item ">
					<view class="m-label">
						<text>联系电话</text>
					</view>
					<view class="m-txt">
						<view class="input-box">
							<input type='number' placeholder='用于接受通知' v-model="order_phone"></input>
						</view>
					</view>
				</view>
				<view class="li-item ">
					<view class="m-label">
						<text>预计到店</text>
					</view>
					<view class="m-txt">
						<view class="input-box">
							<uni-data-select
							  mode="none"
							  v-model="go_hotel_time"
							  :localdata="timelist"
							  @change="changeTime"
							  placeholder="请选择到店时间"
							></uni-data-select>
						</view>
					</view>
					<!-- <view class="icon-arrow iconfont icon-ic_right"></view> -->
				</view>
			</view>
			<view class="bg-white p-20 mt-10 ml-10 mr-10 br-10" >
				<view class="ft-w700 text-black  text-16 ">订单明细</view>
				<view class="display-flex display-flex-justify-space-between mt-10">
					<view class="color-999">
						订单金额
					</view>
					<view class="text-14 text-black ft-w500">
						<text class="mr-5"><text class="text-10">￥</text>{{totalPrice}}</text>
						<text>{{roomNum}}间</text>
						<text>{{dayCount}}晚</text>
					</view>
				</view>
				<view class="display-flex display-flex-justify-space-between mt-10" v-for="(day,dayIndex) in price_details" :key="dayIndex">
					<view class="color-999">
						{{day.date}}
					</view>
					<view class="text-14 text-black ft-w500">
						<text>{{day.room_count}}</text>
						<text>x</text>
						<text class="ml-5"><text class="text-10">￥</text>{{day.price}}</text>
					</view>
				</view>
			</view>
			
			<view  class='footer acea-row row-between-wrapper'>
				<view class="footer_count">
					<view class="acea-row">
						<view>合计:</view>
						<view class='pColor'>
							<priceFormat :price="totalPrice" weight intSize="48" floatSize="32" labelSize="32"></priceFormat>
						</view>

					</view>

				</view>
				<view class='settlement' style='z-index:100'
					@tap="SubOrder">立即结算</view>
			</view>
			
		</view>
		<select-passenger
		     v-if="passengerList.length"
		     ref="selectPassenger"
		     @editPassenger="editPa" 
		    :passengerNum="roomNum"
		     :display="showSelectPassenger"
		    @addPa="addPa"
		    @changePassenger="changePassenger" 
		    @changeClose="showSelectPassenger=false" 
		    :list="passengerList"
		   ></select-passenger>
		<add-passenger  :display="showAddPassenger" :passenger="passenger"  @changeClose="closeAddPassenger"></add-passenger>
			<wloading  ref="loading"  />
	</view>
</template>
<script>
	
	import { mapGetters } from "vuex";
	import { toLogin } from '@/libs/login.js';
	import { configMap } from '@/utils';
	import { getHotelRoomDetailApi, getHotelPackageDetailApi, calculatePriceApi, createOrderApi} from '@/api/hotel'
	import numberBox from '@/components/number-box/index.vue';
	import selectPassenger from './components/selectPassenger/index.vue';
	import addPassenger from './components/addPassenger/index.vue';
	import {
		getUserInfo,
		getPassengerList

	} from '@/api/user.js';
   
	export default {
		components: {
			numberBox,
			selectPassenger,
			addPassenger,
		},
		filters: {
			
		},
		data() {
			return {
				from: '',
				payType: 'weixin', //支付方式
				hotel_id:'',
				room_type_id: '',
				package_id:'',
				start_date:'',
				end_date:'',
				mdStartDate: '',
				mdEndDate: '',
				mdStartDateDsc: '',
				mdEndDateDsc: '',
				dayCount: '',
				hotelInfo:'',
				roomInfo: '',
				packageInfo:'',
				roomNum: 1,
				roomNameList: [
					{
						roomKey: 1,
						roomName: '' 
					}
				],
		
				timelist: [
					{
						value: '14:00',
						text: '14:00'
					},
					{
						value: '15:00',
						text: '15:00'
					}, {
						value: '16:00',
						text: '16:00'
					},
					{
						value: '17:00',
						text: '17:00'
					}, {
						value: '18:00',
						text: '18:00'
					},
					{
						value: '19:00',
						text: '19:00'
					}, {
						value: '20:00',
						text: '20:00'
					},
					{
						value: '21:00',
						text: '21:00'
					}, {
						value: '22:00',
						text: '22:00'
					},
					{
						value: '23:00',
						text: '23:00'
					},
					{
						value: '次日01:00',
						text: '次日01:00'
					},
					{
						value: '次日02:00',
						text: '次日02:00'
					},
					{
						value: '次日03:00',
						text: '次日03:00'
					},
					{
						value: '次日04:00',
						text: '次日04:00'
					},
					{
						value: '次日05:00',
						text: '次日05:00'
					},
					{
						value: '次日06:00',
						text: '次日06:00'
					},
				],
				
				go_hotel_time: "",
				userInfo: '',
				order_phone: '',
				totalPrice: 0,
				price_details: [],
				passengerList: [],
				showSelectPassenger: false,
				showAddPassenger: false,
				passenger: {},
				isSubOrder: false,
				remark: '',
				
			};
		},
		computed: {
			...mapGetters(['isLogin','viewColor']),
			...configMap(['hide_mer_status', 'alipay_open', 'yue_pay_status']),
		},

		onReady() {
		},
		mounted: function() {
		},
		// 单房差不需要 添加乘客
		watch: {
			
		},
		onLoad: function(options) {
			
			if (!this.isLogin) {
				toLogin()
				return
			}
			// #ifdef H5
			this.from = this.$wechat.isWeixin() ? 'weixin' : 'h5'
			// #endif
			// #ifdef MP
			this.from = 'routine'
			// #endif
			// #ifdef APP-PLUS
			this.from = 'weixin'
			// #endif
			if (!options.hotel_id ) return this.$util.Tips({
				title: '请选择酒店'
			}, {
				tab: 3,
				url: 1
			});
			if (!options.room_type_id ) return this.$util.Tips({
				title: '请选择房型'
			}, {
				tab: 3,
				url: 1
			});
			if (!options.package_id ) return this.$util.Tips({
				title: '请选择套餐'
			}, {
				tab: 3,
				url: 1
			});
			if (!options.start_date ) return this.$util.Tips({
				title: '请选择入住日期'
			}, {
				tab: 3,
				url: 1
			});
			if (!options.end_date ) return this.$util.Tips({
				title: '请选择离店日期'
			}, {
				tab: 3,
				url: 1
			});
			this.hotel_id = options.hotel_id;
			this.room_type_id = options.room_type_id;
			this.package_id = options.hotel_id;
			this.start_date = options.start_date;
			this.end_date = options.end_date;
			
			this.dayCount =  this.calculateStayDays(this.start_date,this.end_date);
			this.mdStartDate = this.ymdToMd(this.start_date);
			this.mdEndDate = this.ymdToMd(this.end_date);
			this.mdStartDateDsc =  this.formatDateToRelative(this.start_date);
			this.mdEndDateDsc =  this.formatDateToRelative(this.end_date);
			
			this.getPackageDetail();
			
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			let that = this;
			if (this.isLogin  ) {
				this.$nextTick(function() {
		
					this.getUserInfo();
					this.initPassengerList();
				})
			}
		
		},
		methods:{
			calculatePrice(){
				calculatePriceApi({
					package_id: this.package_id,
					check_in_date: this.start_date,
					check_out_date: this.end_date,
					room_count: this.roomNum
				}).then(res => {
			
				  console.log(111,res.data)
				  this.totalPrice = res.data.amount.total_amount;
				  this.price_details = res.data.price_details;
									
				}).catch(err => {
					
					this.$util.Tips({
						title:err
					},{
						tab: 3,
						url: 1
					})
				})
			},
			
			SubOrder: function(e) {
				if(this.isSubOrder) return;
				let that = this, data = {};
				if (!that.payType) return that.$util.Tips({
					title: '请选择支付方式'
				});
				if(!this.order_phone){
					return that.$util.Tips({
						title: '需要填写联系电话'
					});
				}
				if(!this.go_hotel_time){
					return that.$util.Tips({
						title: '请选择预计到店时间'
					});
				}
						
				if(this.roomNum < 1){
					return that.$util.Tips({
						title: '至少购买一个产品'
					});
				}
				if(!this.roomNameList.length){
					return that.$util.Tips({
						title: '需要填写入住客人信息'
					});
				}
							
			
			    if(this.roomNum > this.roomNameList.length){
					return that.$util.Tips({
						title: '还需要填写'+(this.roomNum - this.roomNameList.length)+'入住客人信息'
					});
				}
				if(this.roomNum < this.roomNameList.length){
					return that.$util.Tips({
						title: '请检入住客人是否正确'
					});
				}
				if(this.totalPrice <=0){
					return that.$util.Tips({
						title: '支付金额不正确！'
					});
				}
				for (var index = 0; index < this.roomNameList.length; index++) {
					var element = this.roomNameList[index];
					if(!element.roomName){
						return that.$util.Tips({
								title: '第'+(index+1)+'入住客人信息未填写'
							});
						}
					}
					
				
	
				

				
				data = {
					hotel_id: this.hotel_id,
					room_type_id: this.room_type_id,
					package_id: this.package_id,
					check_in_date: this.start_date,
					check_out_date: this.end_date,
					room_count: this.roomNum,
					guest_phone: this.order_phone,
					go_hotel_time: this.go_hotel_time,
					room_name_list: this.roomNameList,
					pay_type: this.payType,
					remark: this.remark
				};
				
				if (data.payType == 'balance' && parseFloat(that.userInfo.now_money) < parseFloat(that.totalPrice))
					return that.$util
						.Tips({
							title: '余额不足！'
						});
				uni.showLoading({
					title: '订单支付中',
					mask: true
				});			
				// openPaySubscribe().then(() => {
				// 	that.payment(data);
				// });
				// #ifdef MP-WEIXIN
				// openTourPaySuccessSubscribe().then(() => {
					
				// });
				that.payment(data);
				// that.payment(data);
				// #endif
				
				// #ifdef MP-BAIDU
				// swan.subscribeService({
				//     templateId: 'BD0032',
				//     subscribeId: 'BAIDU_TOUR_PAY_SUCCESS_TO_USER',
				//     type: 'query',
				//     success(res) {
				// 		console.log('res',res)
				//        that.payment(data);
				//     },
				//     fail(err) {
				// 		console.log('err',err)
				//        that.payment(data);
				//     }
				// })
			    that.payment(data);
				// #endif
				
				// #ifdef MP-ALIPAY 
				that.payment(data);
				// #endif
			},
			payment: function(data) {
				let that = this;
				console.log('data',data)
				this.isSubOrder = true;
				createOrderApi(data).then(res => {
						this.isSubOrder = false;
					uni.navigateTo({
						url: `/pages/users/order_hotel_payment/index?order_id=${res.data.order_id}&from_type=order`
					})
					uni.hideLoading();
					return
					
				}).catch(err => {
					this.isSubOrder = false;
					uni.hideLoading();
					return that.$util.Tips({
						title: err
					});
				});
			},
			
			
			// 获取个人信息
			getUserInfo() {
				getUserInfo().then(res => {
					console.log('this.userInfo',res.data)
					this.userInfo = res.data;
					this.order_phone = this.userInfo.phone;
				})
			},
			changeTime(e) {
			      console.log("e:", e);
			},
			minusNum(num, index){
				this.roomNum = num;
				if(this.roomNum > 1) {
					this.roomNameList.pop();
				}
				
				console.log('this.roomNameList1',this.roomNameList)
				this.calculatePrice()
			},
			addNum(num, index){
				this.roomNum = num;
				this.roomNameList.push({
					roomKey: this.roomNum,
					roomName: ''
				});
				console.log('this.roomNameList2',this.roomNameList)
				this.calculatePrice()
			},
			getPackageDetail(id){
				var that = this;
				this.$refs.loading.open();
				
				getHotelPackageDetailApi(this.package_id).then(res => {
			
				    this.packageInfo = res.data;
					this.hotelInfo = res.data.hotel;
				    this.roomInfo = res.data.roomType;
					this.calculatePrice()				
					this.$refs.loading.close();
				}).catch(err => {
					this.$refs.loading.close();
					this.$util.Tips({
						title:err
					},{
						tab: 3,
						url: 1
					})
				})
			},
			
			initPassengerList(){
				let that = this
				getPassengerList().then(res => {
					that.passengerList = res.data
					var data = res.data;
					if(data.length){
						that.passengerList.forEach(function(res,index) {
							that.passengerList[index].check = false
						});
					
					}
					
				})
			},
			selectPaShow(){
				var that = this;
				console.log(122112)
				that.passengerList.forEach(function(res,indexe) {
					that.passengerList[indexe].check = false
				})
				this.showSelectPassenger = true;
			},
			changePassenger(data,skuIndex){
				console.log('data',data)
				for (var i = 0; i <this.passengerList.length; i++ ) {
					this.passengerList[i].check = false;
				}
				
				if(data.length){
					for (var i = 0; i <this.roomNameList.length; i++ ) {
						if(data[i]){
							this.roomNameList[i] = {
								roomKey: i+1,
								roomName: data[i].name
							} 
						} else {
							this.roomNameList[i] = {
								roomKey: i+1,
								roomName:''
							}
						}
						
					}
					
				}
				 this.showSelectPassenger = false;
			},
			editPa(item){
				this.passenger = item;
				this.showAddPassenger = true;
			},
			
			addPa(){
				this.showSelectPassenger = false;
				this.showAddPassenger = true;
			},
			closeAddPassenger(){
				this.showAddPassenger = false;
				this.initPassengerList();
			},
			calculateStayDays(checkinDateStr, checkoutDateStr) {
			  // 1. 解析日期为 Date 对象
			  const checkinDate = new Date(checkinDateStr);
			  const checkoutDate = new Date(checkoutDateStr);
			  
			  // 2. 验证日期有效性（格式是否正确）
			  if (isNaN(checkinDate.getTime()) || isNaN(checkoutDate.getTime())) {
			    return "无效日期，请使用 YYYY-mm-dd 格式";
			  }
			  
			  // 3. 统一设置时间为 00:00:00，仅比较“年月日”
			  checkinDate.setHours(0, 0, 0, 0);
			  checkoutDate.setHours(0, 0, 0, 0);
			  
			  // 4. 检查离店日期是否晚于入住日期
			  if (checkoutDate <= checkinDate) {
			    return "离店日期必须晚于入住日期";
			  }
			  
			  // 5. 计算天数差（毫秒差转换为天数）
			  const timeDiff = checkoutDate - checkinDate; // 毫秒差
			  const days = timeDiff / (1000 * 60 * 60 * 24); // 转换为天数
			  
			  // 返回整数天数（因时间已统一为0点，结果必为整数）
			  return Math.floor(days);
			},
			formatDateToRelative(dateStr) {
			  // 解析目标日期并验证有效性
			  const targetDate = new Date(dateStr);
			  if (isNaN(targetDate.getTime())) {
			    return "无效日期（格式应为 YYYY-mm-dd）";
			  }
			  
			  // 统一将时间设为 00:00:00，避免时分秒影响
			  targetDate.setHours(0, 0, 0, 0);
			  
			  // 获取今天的日期（同样设为 00:00:00）
			  const today = new Date();
			  today.setHours(0, 0, 0, 0);
			  
			  // 计算两个日期的天数差
			  const timeDiff = targetDate - today;
			  const dayDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
			  
			  // 判断并返回结果
			  if (dayDiff === 0) {
			    return "今天";
			  } else if (dayDiff === 1) {
			    return "明天";
			  } else if (dayDiff === 2) {
			    return "后天";
			  } else {
			    // 转换为星期几（getDay() 返回 0-6，0 是周日，1 是周一...）
			    const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
			    return weekdays[targetDate.getDay()];
			  }
			},
			ymdToMd(ymdStr) {
			  // 分割字符串为 [年, 月, 日]
			  const parts = ymdStr.split('-');
			  // 校验格式是否正确（避免非 yyyy-m-d 格式的输入）
			  if (parts.length !== 3) {
				return this.$util.Tips({title: '请输入正确的 yyyy-m-d 格式日期'})
			  }
			  // 拼接 月-日 并返回
			  return `${parts[1]}-${parts[2]}`;
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	.text-cancel{
		color: var(--view-theme);
	}
	.source_content{
		 justify-content: flex-start;
		line-height: 24px;
	}
	.choice_options_wrapper{
		align-items: flex-end;
	}
	.li-item{
		min-height: 44px;
		line-height: 1.2;
		position: relative;
		display: flex;
		align-items: center;
		border-bottom: 0.5px solid #efefef;
		font-size: 14px;
	}
	.li-item:last-child {
	    border-bottom: 0;
	}
	.name-box {
	    flex: 1;
	}
	.name-box .name-item {
	    display: flex;
	    align-items: center;
	}
	.name-box .name-item:not(:last-child) {
	    border-bottom: .5px solid #efefef;
	}
	
	.li-item .m-label {
	    width: 90px;
	    min-height: 44px;
	    box-sizing: border-box;
	    color: #666;
	    display: flex;
	    align-items: center;
	    align-self: flex-start;
	}
	.li-item .m-input, .li-item .m-txt {
	    color: #111;
	}
	.li-item .m-txt {
	    flex: 1;
	}
	.li-item .input-box {
	    height: 44px;
	    display: flex;
	    align-items: center;
	}
	.guest-icon {
	    font-size: 22px;
	    color: var(--view-theme);
	    padding: 10px;
	    margin-right: 10px;
	}
	.icon-arrow {
	    width: 22px;
	    text-align: center;
	    font-size: 10px;
	}
	.footer {
		width: 100%;
		height: 100rpx;
		height: calc(120rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		height: calc(120rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
		background-color: #fff;
		padding: 0 30rpx;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 30;
		.footer_count{
			font-size: 28rpx;
			>view {
				align-items: baseline;
			}
			.pColor {
				margin-left: 12rpx;
			}
		}
		.coupon_price{
			color: #999999;
			font-size: 22rpx;
			margin-top: 10rpx;
			text{
				color: #666666;
				background: #F5F5F5;
				border-radius: 26rpx;
				margin-left: 20rpx;
				height: 34rpx;
				line-height: 34rpx;
				display: inline-block;
				width: 104rpx;
				text-align: center;
				font-size: 18rpx;
			}
		}
	}
	.pColor{
		color: var(--view-priceColor);
	}
	.footer .settlement {
		font-size: 30rpx;
		color: #fff;
		width: 200rpx;
		height: 72rpx;
		background-color: var(--view-priceColor);
		border-radius: 60rpx;
		text-align: center;
		line-height: 72rpx;
		font-size: 26rpx;
		&.disabled {
			background-color: #cccccc;
		}
	}
</style>